package cn.edu.sjtu.book.service.impl;

import javax.persistence.NoResultException;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.sjtu.book.dao.UserDao;
import cn.edu.sjtu.book.entity.User;
import cn.edu.sjtu.book.service.UserManager;
import cn.edu.sjtu.book.service.exception.UserInvalidPasswordException;
import cn.edu.sjtu.book.service.exception.UserNotExistsException;

@Service
@Transactional
public class UserManagerImpl implements UserManager {
	
	private static Logger logger = LoggerFactory.getLogger(UserManagerImpl.class);

	@Autowired
	private UserDao userDao;

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public User getUser(Long id) {
		logger.debug("getting user: " + id);
		return userDao.get(id);
	}

	public void saveUser(User user) {
		logger.debug("saving user: " + user);
		userDao.save(user);
	}

	@Transactional(rollbackFor = { UserNotExistsException.class, UserInvalidPasswordException.class } )
	public User authenticate(User user) throws UserNotExistsException, UserInvalidPasswordException {
		User aUser = null;
		try {
			aUser = userDao.findUserByLoginName(user.getLoginName());
		} catch (NoResultException e) {
			throw new UserNotExistsException(e);
		}
		
		if (aUser == null) throw new UserNotExistsException();
		
		logger.debug("checking password");
		if (StringUtils.isEmpty(user.getPassword()) || !user.getPassword().equals(aUser.getPassword())) {
			// user password invalid
			logger.debug("invalid password");
			throw new UserInvalidPasswordException();
		}
		
		return aUser;
	}

}
